package com.dlc.shop.user.common.listener;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.dlc.shop.allinpay.listener.CreateAllinpayMemberListener;
import com.dlc.shop.bean.enums.UserBalanceLogType;
import com.dlc.shop.bean.event.allinpay.AllinpayBalanceUpdateEvent;
import com.dlc.shop.bean.model.UserExtension;
import com.dlc.shop.common.allinpay.constant.PaySysType;
import com.dlc.shop.security.common.util.AuthUserContext;
import com.dlc.shop.service.UserExtensionService;
import com.dlc.shop.user.common.model.UserBalanceLog;
import com.dlc.shop.user.common.service.UserBalanceLogService;
import lombok.AllArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Objects;

/**
 * @author gaozijie
 * @date 2023-08-11
 */
@Component
@AllArgsConstructor
public class AllinpayUserBalanceUpdateListener {

    private static final Logger logger = LoggerFactory.getLogger(CreateAllinpayMemberListener.class);

    private final UserBalanceLogService userBalanceLogService;
    private final UserExtensionService userExtensionService;

    /**
     * 更新通联用户余额
     * @param event
     */
    @EventListener(AllinpayBalanceUpdateEvent.class)
    public void updateAllinpayUserBalance(AllinpayBalanceUpdateEvent event) {
        if (Objects.isNull(event.getUserId())) {
            event.setUserId(AuthUserContext.getUserId());
        }
        // 更新通联余额
        if (!Objects.equals(event.getIsUpdateBalance(), false)) {
            this.updateUserBalance(event);
        }
        // 插入用户余额日志
        if (!Objects.equals(event.getIsAddLog(), false)) {
            this.insertBalanceLog(event);
        }
        // 更新余额日志为"已支付"
        if (Objects.nonNull(event.getPayNo()) && event.isPay()) {
            this.updateBalanceLog(event);
        }
    }

    /**
     * 插入余额日志
     * @param event
     */
    private void insertBalanceLog(AllinpayBalanceUpdateEvent event) {
        UserBalanceLog userBalanceLog = new UserBalanceLog();
        userBalanceLog.setUserId(event.getUserId());
        userBalanceLog.setPayNo(event.getPayNo());
        userBalanceLog.setChangeBalance(Math.abs(event.getChangeBalance()));
        userBalanceLog.setIoType(event.getChangeBalance() >= 0 ? 1 : 0);
        userBalanceLog.setType(event.getType());
        userBalanceLog.setCreateTime(new Date());
        userBalanceLog.setIsPayed(Objects.isNull(event.getPayNo()) ? 1 : 0);
        userBalanceLog.setPaySysType(PaySysType.ALLINPAY.value());
        userBalanceLogService.save(userBalanceLog);
    }

    /**
     * 更新余额日志（已支付）
     * @param event
     */
    private void updateBalanceLog(AllinpayBalanceUpdateEvent event) {
        UserBalanceLog balanceLog = userBalanceLogService.getOne(new LambdaQueryWrapper<UserBalanceLog>()
                .eq(UserBalanceLog::getPayNo, event.getPayNo()));
        if (Objects.isNull(balanceLog)) {
            return;
        }
        balanceLog.setIsPayed(1);
        userBalanceLogService.updateById(balanceLog);
    }

    /**
     * 更新用户余额
     * @param event
     */
    private void updateUserBalance(AllinpayBalanceUpdateEvent event) {
        UserExtension userExtension = userExtensionService.getOne(new LambdaQueryWrapper<UserExtension>()
                .eq(UserExtension::getUserId, event.getUserId()));
        if (Objects.isNull(userExtension)) {
            logger.error("用户[{}]更新通联余额失败，原因：userExtension不存在", event.getUserId());
            return;
        }
        // 修改通联余额（余额增加，累计余额也进行计算[退款余额不计入累计余额中]）
        if (event.getChangeBalance() > 0
                && !Objects.equals(event.getType(), UserBalanceLogType.REFUND.value())) {
            userExtension.setAllinpayBalance(userExtension.getAllinpayBalance() + event.getChangeBalance());
        }
        userExtension.setAllinpayTotalBalance(userExtension.getAllinpayTotalBalance() + event.getChangeBalance());
        userExtensionService.updateByUserId(userExtension);
    }
}
